package com.topisv.tms.api;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.topisv.tms.service.stock.instorage.InstorageBillService;
import com.topisv.tms.service.transporter.TransporterService;
import com.topisv.tms.utils.SystemUtil;

/**
 * wms外部系统API
 * 
 * @author calvin
 */
@Controller
@RequestMapping(value = "/api")
public class WMSAPIController {

	private static final Logger logger = LoggerFactory.getLogger(WMSAPIController.class);
	
	@Autowired
	private InstorageBillService instorageBillService;
	
	@Autowired
	private TransporterService transporterService;

	/**
	 * 创建入库单接口
	 * @param appkey  密钥
	 * @param appsecret 密文
	 * @param data 入库单信息数据（json格式）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "createInstorageBill", method = RequestMethod.POST)
	public void createInstorageBill(
			@RequestParam(value = "appkey") String appkey,
			@RequestParam(value = "appsecret") String appsecret,
			@RequestParam(value = "data") String data,
			HttpServletRequest request, HttpServletResponse response) {

		logger.info("外部接口调用:创建入库单");
		logger.info("=================================================外部接口调用:创建入库单 start=================================================");
		logger.info("【appkey】" + appkey);
		logger.info("【appsecret】" + appsecret);
		logger.info("【data】"+ data);
		logger.info("=================================================外部接口调用:创建入库单 end ==================================================");

		Map<String,String> map = new HashMap<String,String>();
		ObjectMapper objectMapper = new ObjectMapper();
		JSONObject json = null;
		try {
			
			String md5 = SystemUtil.MD5(data + appkey);
			String base64 = SystemUtil.getBASE64(md5);
			
			if(!base64.equals(appsecret)){  //身份验证通过
				map.put("state", "false");
				map.put("reason", "签名验证失败");
			}else{           //身份验证不通过
				
				//创建入库单
				json = JSONObject.fromObject(data);
				String customerCode = json.getString("customerCode"); //商家编码
				String warehouseCode = json.getString("warehouseCode"); //入仓编码
				String boxNum=json.getString("boxNum"); //箱子数量
				String skuNum=json.getString("skuNum"); //商品种类（有多少种sku）
				String goodsNum=json.getString("goodsNum"); //商品总数
				String aboutCode = json.getString("aboutCode"); //相关单号：如商家的出库单号
				String remarks = json.getString("remarks"); //备注信息
				
				Map<String, String> result=this.instorageBillService.createInstorageBill_API(customerCode,warehouseCode,boxNum,skuNum,goodsNum,aboutCode,remarks);
				String msg=result.get("msg");
				
				if("success".equals(msg)){
					map.put("state", "true");
					map.put("reason", "Successfully created");
					String billCode=result.get("billCode");
					map.put("billCode", billCode);
					
				}else{
					map.put("state", "false");
					map.put("reason", "Creation failed");
				}
				
			}
			
			objectMapper.writeValue(response.getWriter(), map);
			
		} catch (Exception e) {
			map.put("state", "false");
			map.put("reason", "Server exception");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e2) {
				logger.info("JSON format error");
			}
		}
	}
	
	
	/**
	 * 创建商品信息接口
	 * @param appkey  密钥
	 * @param appsecret 密文
	 * @param data 入库单信息数据（json格式）
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "createGoodsInfo", method = RequestMethod.POST)
	public void createGoodsInfo(
			@RequestParam(value = "appkey") String appkey,
			@RequestParam(value = "appsecret") String appsecret,
			@RequestParam(value = "data") String data,
			HttpServletRequest request, HttpServletResponse response) {

		logger.info("外部接口调用:创建商品信息接口");
		logger.info("=================================================外部接口调用:创建商品信息 start=================================================");
		logger.info("【appkey】" + appkey);
		logger.info("【appsecret】" + appsecret);
		logger.info("【data】"+ data);
		logger.info("=================================================外部接口调用:创建商品信息 end ==================================================");

		Map<String,String> map = new HashMap<String,String>();
		ObjectMapper objectMapper = new ObjectMapper();
		JSONObject json = null;
		try {
			
			String md5 = SystemUtil.MD5(data + appkey);
			String base64 = SystemUtil.getBASE64(md5);
			
			if(!base64.equals(appsecret)){  //身份验证通过
				map.put("state", "false");
				map.put("reason", "签名验证失败");
			}else{           //身份验证不通过
				
				//创建商品信息
				json = JSONObject.fromObject(data);
				String customerCode = json.getString("customerCode"); //商家编码
				String sku = json.getString("sku"); //SKU编码
				String barCode = json.getString("barCode"); //规格代码，如果无此代码，可与sku编码相同
				String barName = json.getString("barName"); //规格名称
				String goodsName = json.getString("goodsName"); //商品名称
				String GW = json.getString("GW"); //毛重
				String NW = json.getString("NW"); //净重
				String length = json.getString("length"); //长
				String width = json.getString("width"); //宽
				String height = json.getString("height"); //高
				String color = json.getString("color"); //颜色
				String size = json.getString("size"); //尺寸
				
				
				String msg=this.instorageBillService.createGoodsInfo_API(
						customerCode,sku,barCode,barName,
						goodsName,GW,NW,
						length,width,height,
						color,size
					);
				
				if("success".equals(msg)){
					map.put("state", "true");
					map.put("reason", "Successfully created");
				}
				else if("null_customerCode".equals(msg)){
					map.put("state", "false");
					map.put("reason", "customerCode is null");
				}
				else if("null_sku".equals(msg)){
					map.put("state", "false");
					map.put("reason", "sku is null");
				}
				else if("null_barCode".equals(msg)){
					map.put("state", "false");
					map.put("reason", "barCode is null");
				}
				else{
					map.put("state", "false");
					map.put("reason", "Creation failed");
				}
			}
			
			objectMapper.writeValue(response.getWriter(), map);
			
		} catch (Exception e) {
			map.put("state", "false");
			map.put("reason", "Server exception");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e2) {
				logger.info("JSON format error");
			}
		}
	}
	
	/**
	 * 提供给交叉传送带的订单数据
	 * @author <a href=mailto:zhuangcaijin@nryuncang.com>Fisher</a>
	 * @version 1.0.0
	 */
	@RequestMapping(value = "getOrderForTransporter")
	public void getOrderForTransporter(
			/*@RequestParam(value = "appkey", ) String appkey,
			@RequestParam(value = "appsecret") String appsecret,
			@RequestParam(value = "data") String data,*/
			HttpServletRequest request, HttpServletResponse response) {

		Map<String,Object> map = new HashMap<String,Object>();
		ObjectMapper objectMapper = new ObjectMapper();
		JSONObject json = null;
		try {
			
			/*String md5 = SystemUtil.MD5(data + appkey);
			String base64 = SystemUtil.getBASE64(md5);
			
			if(!base64.equals(appsecret)){
				map.put("state", "false");
				map.put("reason", "签名验证失败");
			}else{*/
			List ediOrderList = transporterService.getEdiOrderList();
			map.put("state", "true");
			map.put("data", ediOrderList);
			
			objectMapper.writeValue(response.getWriter(), map);
		} catch (Exception e) {
			map.put("state", "false");
			map.put("reason", "Server exception");
			try {
				objectMapper.writeValue(response.getWriter(), map);
			} catch (Exception e2) {
				logger.info("JSON format error");
			}
		}
	}

}
